package service

import (
	"alan-snippet/internal/dao"
	"alan-snippet/internal/dto"
	"alan-snippet/internal/models"
	"errors"

	"golang.org/x/crypto/bcrypt"
)

func RegisterUser(registerRequestDto *dto.RegisterRequestDTO) (*models.User, error) {
	// check whether user exist?
	_, err := dao.GetUserByEmail(registerRequestDto.Email)
	if err == nil {
		return nil, errors.New("用户存在")
	}

	// encrypt password
	hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(registerRequestDto.Password), bcrypt.DefaultCost)

	// register and save
	user := &models.User{
		Email:    registerRequestDto.Email,
		Password: string(hashedPassword),
	}
	user, err = dao.CreateUser(user)
	if err != nil {
		return nil, err
	}

	return user, nil
}

func LoginUser(login *dto.LoginRequestDTO) (*models.User, error) {
	// check username,password
	user, err := dao.GetUserByEmail(login.Email)
	if err != nil {
		return nil, errors.New("用户不存在，请先注册")
	}

	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(login.Password))
	if err!=nil {
		return nil,errors.New("用户名和密码不匹配，请重试")
	}

	return user,nil
}
